﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net.Mail;
using System.Net;

using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Autodiscover;

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Data;

namespace Imap
{
    
    public class KoExchWebService
    {

        #region Members
        public string ExcServiceUrlStr
        {
            get
            {
                return @"https://mail01.korablik.local/EWS/Exchange.asmx";
            }
        }
        #endregion

        #region Constructors
        
        #endregion

        #region Common Methods

        Folder ListFoldersInInbox(ref ExchangeService service, ref Folder f, string parFolderName = "Опрос с сайта")
        {
            Folder ret = null;
            int itemCount = 1;
            if (f.ChildFolderCount <= 0)
                return ret;
            itemCount = f.ChildFolderCount;
            FindFoldersResults findResults = service.FindFolders(f.Id, new FolderView(itemCount));
            foreach (Folder folder in findResults.Folders)
            {
                if (folder.DisplayName == parFolderName)
                {
                    ret = folder;
                    return ret;
                }
            }
            return ret;
        }

        bool FindShopNameInMsgBody(EmailMessage msg, ref DataTable tblShops, ref string strName)
        {
            bool bFound = false;
            string msgBodyText = msg.Body.Text;

            foreach (DataRow r in tblShops.Rows)
            {
                if (r["ShopName"] == DBNull.Value)
                    continue;
                string strTmp = (string)r["ShopName"];
                if (String.IsNullOrEmpty(strTmp))
                    continue;

                strTmp = strTmp.Trim();
                string strLower = strTmp.ToLower();

                if (msgBodyText.IndexOf(strTmp) >= 0 || msgBodyText.IndexOf(strTmp) >= 0)
                {
                    bFound = true;
                    strName = strTmp;
                    break;
                }
            }
            return bFound;
        }

        #endregion

        #region SP

        public Exception Get_SP_Q_Msg(string parUID, string parPWD, string parDomainName, string parAutodiscoverUrl, string parInBoxName = "in@korablik.ru")
        {

            #region Members

            Exception ret = null;
            DateTime dtLast = new DateTime();
            Ko2.Portal.Env env = new Ko2.Portal.Env();
            env.GetWebSetting_ShopsDiscussion_LastSuccessfully(ref dtLast);
            List<EmailMessage> msgList = new List<EmailMessage>();

            #endregion

            try
            {

                #region Init

                // Connect to Exchange Web Services as user1 at contoso.com.
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(parUID, parPWD, parDomainName);
#if DEBUG
                service.TraceEnabled = true;
#else
                service.TraceEnabled = false;
#endif

                //service.AutodiscoverUrl(parAutodiscoverUrl);
                service.Url = new Uri(ExcServiceUrlStr);
                

                // In Folder
                Folder folder = Folder.Bind(service, new FolderId(WellKnownFolderName.Inbox, parInBoxName));

                Folder f2 = ListFoldersInInbox(ref service, ref folder);
                if (f2 == null)
                    return ret;


                #endregion Init

                #region Find Init

                //string subject = @"Опрос покупателей";
                string subject2 = @"Отзывы покупателей магазинов Кораблик.";

                ItemView view = new ItemView(f2.TotalCount);
                view.PropertySet = new PropertySet() { RequestedBodyType = BodyType.Text };

                #endregion Find Init

                #region Find Msgs - While

                #region while

                FindItemsResults<Item> findResults;
                do
                {

                    #region Find Criteria

                    SearchFilter sf = new SearchFilter.SearchFilterCollection(
                        LogicalOperator.And
                        , new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, subject2)
                        , new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, dtLast)
                        );

                    findResults = service.FindItems(
                        f2.Id
                        , sf
                        , view);

                    service.LoadPropertiesForItems(findResults, PropertySet.FirstClassProperties);

                    #endregion find criteria

                    #region foreach
                    foreach (Item item in findResults)
                    {
                        // Get all properties of email message
                        PropertySet pset = new PropertySet(BasePropertySet.FirstClassProperties);
                        // Get the body in text
                        pset.RequestedBodyType = Microsoft.Exchange.WebServices.Data.BodyType.HTML;
                        // Do an Item.Bind() to retrieve the Item
                        EmailMessage msg = Item.Bind(service, item.Id, pset) as EmailMessage;

                        // Refresh
                        //msg.Load();

                        if (!String.IsNullOrEmpty(msg.Body.Text))
                        {

                            DateTime dtTmp = msg.DateTimeReceived;
                            if (dtLast < dtTmp)
                                dtLast = dtTmp;

                            msgList.Add(msg);
                        }
                    }
                    #endregion foreach

                } while (findResults.MoreAvailable);

                #endregion while

                #region Append to SP

                if (msgList.Count > 0)
                {
                    bool bFound = false;
                    string strShopName = "";
                    Ko2.DB.MySql mysql = new Ko2.DB.MySql();
                    DataTable tblShops = new DataTable();
                    mysql.GetShopNames(ref tblShops);

                    foreach (EmailMessage msg in msgList)
                    {
                        strShopName = "";
                        string msgBodyText = msg.Body.Text;

                        bFound = FindShopNameInMsgBody(msg, ref tblShops, ref strShopName);

                        //if (bFound == false)
                        //    continue;

                        SP_Shops_QA_List_Ins(DateTime.Now
                            , @"Отзывы покупателей магазинов Кораблик"
                            , strShopName
                            , msgBodyText);
                    }
                }

                #endregion Append to SP

                env.SetWebSetting_ShopsDiscussion_LastSuccessfully(dtLast);

                #endregion While

            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            return ret;
        }

        Exception SP_Shops_QA_List_Ins(DateTime parDT, string parTitle, string parShopName, string parBody)
        {
            Exception ret = null;
            Ko2.Portal.Env env = new Ko2.Portal.Env();
            Ko2.Portal.SP_List.SPList_ShopsDiscussions list = new Ko2.Portal.SP_List.SPList_ShopsDiscussions();
            ret = list.Insert(parDT, parTitle, parShopName, parBody);
            return ret;
        }

        #endregion

    }

}
